package com.share.config.redisson;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisLock {
    @Autowired
    private RedissonClient redissonClient;

    private RLock getLock(String lockKey) {
        return redissonClient.getLock("redis_lock:" + lockKey);
    }

    public void lock(String lockKey) {
        getLock(lockKey).lock();
    }

    public boolean tryLock(String lockKey) {
        return getLock(lockKey).tryLock();
    }

    public boolean tryLock(String lockKey, long time, TimeUnit unit) throws InterruptedException {
        return getLock(lockKey).tryLock(time, unit);
    }

    public boolean tryLock(String lockKey, long secondTime) throws InterruptedException {
        return getLock(lockKey).tryLock(secondTime, TimeUnit.SECONDS);
    }

    public void unlock(String lockKey) {
        getLock(lockKey).unlock();
    }
}
